<script setup lang="ts">
	import { ref, reactive, unref, computed } from 'vue'
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { useNotify } from '@/hooks/web/useNotify/index.js'
	import { carAddPay } from '@/package_saleman/api/Order'

	// 消息弹窗
	const NotifyRef = ref<any>(null)
	const { showNotify } = useNotify(NotifyRef)

	const remark = ref('')

	// 路由参数
	interface RouteParams {
		store_id : string,
		receivable_amount : string,
		id : string,
	}
	const routeParams = ref<RouteParams>({
		store_id: '',
		id: '',
		receivable_amount: ''
	})
	onLoad((options) => {
		routeParams.value = options as RouteParams
		getList(JSON.parse(options.data))
	})
	const receive_type = ref([])
	const useOrderDetail = () => {
		const dataList = ref({})
		const getList = async (option) => {
			// const params = {
			// 	...routeParams.value
			// }
			// const res = await orderSettle(params)
			dataList.value = option;
			// console.log(dataList.value, '提交数据')
		}

		return {
			dataList,
			getList,
		}
	}
	const { dataList, getList } = useOrderDetail()

	const show = ref(false)
	const pay_type = ref(0)
	const pay_name = ref([])
	const sign_amount = ref((0).toFixed(2)); 
	const columns = reactive([
		[
			{
				label: '现金',
				id: 1
			},
			{
				label: '公司账户',
				id: 2
			},
			{
				label: '挂账',
				id: 3
			}
		]
	]);

	const cancel = () => {
		show.value = false
	}

	const confirm = (e) => {
		sign_amount.value = dataList.value.receive_money
		pay_type.value = e.value[0].id
		pay_name.value = e.value[0].label
		show.value = false
	}
	const useUploadImg = () => {
		const certificate = ref<any[]>([])

		// 添加图片
		type UploadImageFile = {
			size : number,
			type : 'image',
			url : string,
			thumb : string
		}
		type UploadImageParams = {
			file : UploadImageFile | UploadImageFile[],
			index : number,
			name : string
		}
		type AddImage = (event : UploadImageParams) => any
		// 新增图片
		const addImage = async (event) => {
			// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file);
			let fileListLen = certificate.value.length;
			lists.map((item) => {
				certificate.value.push({
					...item,
					status: 'uploading',
					message: '上传中',
				});
			});
			for (let i = 0; i < lists.length; i++) {
				const result = await uploadImage(lists[i].url);
				let item = certificate.value[fileListLen];
				certificate.value.splice(fileListLen, 1, {
					...item,
					status: 'success',
					message: '',
					url: result,
				});
				fileListLen++;
			}
		};

		const uploadImage = (url) => {
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: `${process.env.VUE_APP_BASE_URL}/salesman/upload`,
					filePath: url,
					name: 'file',
					header: {
						'content-type': 'application/json;charset=utf-8',
						'token': uni.getStorageSync('trioToken'),
					},
					success: (res) => {
						const data = JSON.parse(res.data)
						if (data.code !== 200) {
							uni.showToast({
								title: `${data.msg},请重新上传!`,
								icon: 'none'
							})
							return
						}
						setTimeout(() => {
							resolve(data.data.url);
						}, 1000);
					},
				});
			});
		};
		// 删除图片
		const delImage = (event : UploadImageParams) => {
			certificate.value.splice(event.index, 1)
		}

		return {
			certificate,
			addImage,
			delImage,
			uploadImage
		}
	}

	const { certificate, addImage, delImage, uploadImage } = useUploadImg()

	const validatePositive = () => {
		// 检查输入是否为有效数字
		if (isNaN(Number(sign_amount.value))) {
			showNotify({
				type: 'error',
				message: '请输入有效的数字金额！'
			});
			sign_amount.value = (0).toFixed(2); // 重置为 0.00
			return false;
		}
		// 检查金额是否为正数
		if (Number(sign_amount.value) < 0) {
			showNotify({
				type: 'error',
				message: '金额必须为正数！'
			});
			sign_amount.value = (0).toFixed(2); // 重置为 0.00
			return false;
		}
		// 检查金额是否大于订单金额
		if (Number(sign_amount.value) > Number(dataList.value.receive_money)) {
			showNotify({
				type: 'error',
				message: '不可以大于订单金额！'
			});
			sign_amount.value = Number(dataList.value.receive_money).toFixed(2);
			return false;
		}
		// 确保 sign_amount 保留两位小数
		sign_amount.value = Number(sign_amount.value).toFixed(2);
	};

	const submitLoading = ref(false)
	const submit = async () => {
		// if (Number(receive_type.value) == 1) {
			if (!receive_type.value.length) {
				showNotify({
					type: 'error',
					message: '请选择收款方式'
				})
				return false
			}
			if (!pay_name.value.length) {
			showNotify({
				type: 'error',
				message: '请选择支付类型'
			})
			return false
		}
			// 图片
			if (certificate.value.length == 0) {
				showNotify({
					type: 'error',
					message: '请上传图片！'
				});
				return false;
			}
		// }
		
		// const params = {
		// 		id: unref(routeParams).id,
		// 		store_id: unref(routeParams).store_id,
		// 		receivable_amount: unref(routeParams).receivable_amount,
		// 		remark: remark.value,
		// 		payment_type: receive_type.value.join(','),
		// 		payment_model: pay_name.value.join(','),
		// 		sign_amount: sign_amount.value,
		// 		certificate: certificate.value.map((item) => item.url).join(',')
		// 	}
			// console.log(params, '提交数据')
		submitLoading.value = true
		try {
			const params = {
				id: unref(routeParams).id,
				store_id: unref(routeParams).store_id,
				receivable_amount: unref(routeParams).receivable_amount,
				remark: remark.value,
				payment_type: receive_type.value.join(','),
				payment_model: pay_name.value.join(','),
				sign_amount: sign_amount.value,
				certificate: certificate.value.map((item) => item.url).join(',')
			}
			const res = await carAddPay(params)
			showNotify({
				type: 'success',
				message: res.msg
			})
			setTimeout(() => {
				submitLoading.value = false
				uni.redirectTo({
					url: `/package_saleman/pages/Carsales/index`
				})
			}, 500)

		} catch (err) {
			showNotify({
				type: 'error',
				message: err.msg
			})
			setTimeout(() => {
				submitLoading.value = false
				uni.redirectTo({
					url: `/package_saleman/pages/Carsales/index`
				})
			}, 500)
			submitLoading.value = false
		}
	}
</script>

<template>
	<view class="content">
		<up-navbar title="车销单" autoBack placeholder></up-navbar>
		<!--<view class="goods-box">
			 <view class="box-header" v-if="dataList">商品详情</view>
			<view class="line"></view> 
			<view class="main-box" v-for="(item, index) in dataList" :key="index">
				<view class="main-left">
					<up-image :show-loading="true" :src="item.goods?.img" width="140rpx" height="140rpx"></up-image>
					<view class="gift" v-if="item.goods_type == 2">赠品</view>
				</view>
				<view class="main-right">
					<view class="right-header">
						<view class="header-name">{{item.goods?.goods_name}}{{item.spec?.spec_name}}</view>
						<view style="color: rgba(155, 157, 159, 1);">
							￥{{item.true_price}}*{{item.num}}{{item.spec?.unit_name}}</view>
					</view>
					<view class="right-mod">{{item.goods?.code69}}</view>
					<view class="right-foot">
						<view style="color: rgba(106, 107, 107, 1);">修改前：<text
								style="color: rgba(36, 34, 34, 1);">￥{{item.sale_price}}</text></view>
						<view style="color: rgba(55, 131, 252, 1);">修改后：￥{{item.true_price}}
						</view>
						<view style="font-size: 28rpx;color: rgba(245, 99, 81, 1);">￥{{item.total_price}}</view>
					</view>
				</view>
			</view> 
		</view>-->
		<!-- 结算方式 -->
		<view class="payment-method">
			<view class="method-header">
				<view class="header-left">收款方式
					<span style="font-size: 10px;
font-weight: 500;
letter-spacing: 0px;
line-height: 14px;
color: rgba(255, 84, 84, 1);">*如需组合支付，请同时勾选组合方式</span>
				</view>
			</view>
			<view class="payment-container">
				<up-checkbox-group v-model="receive_type" placement="row" justify="space-between">
					<up-checkbox :customStyle="{ flex: 1 }" name="1" label="现结"></up-checkbox>
					<up-checkbox :customStyle="{ flex: 1 }" name="2" label="账期"></up-checkbox>
					<up-checkbox :customStyle="{ flex: 1 }" name="3" label="预存款"></up-checkbox>
				</up-checkbox-group>
			</view>
		</view>
		<view>
			<!-- 支付方式 -->
			<view class="payment-method">
				<view class="method-header">
					<view class="header-left">支付类型
					</view>
				</view>
				<view class="method-main">
					<up-checkbox-group v-model="pay_name" iconPlacement="right" placement="column">
						<up-checkbox name="1" label="现金"></up-checkbox>
						<up-checkbox name="2" label="公司账户"></up-checkbox>
						<up-checkbox name="3" label="挂账"></up-checkbox>

					</up-checkbox-group>
				</view>
				<!-- <view class="method-header">
					<view class="header-left">支付类型</view>
					<view class="header-right" @click="show = true">{{pay_name}}></view>
				</view>
				<view class="method-line"></view>
				<view class="method-main">
					<view class="main-name">实际收款</view>
				</view> -->

				<!-- <view class="method-foot" v-if="pay_type == 3">
					<up-text mode="price" text="0"></up-text>
				</view> -->
				<!-- <view class="method-foot">
					<up-input v-model="sign_amount" type="number" placeholder="" border="none" prefixIcon="￥"
						prefixIconStyle="font-size: 15px;" @blur="validatePositive()"></up-input>
				</view> -->
			</view>
			<view class="content-foot">
				<view style="font-size: 32rpx;font-weight: bold;">
					现金收款明细
				</view>
				<view style="border: 1px solid #f0f0f0;padding: 12rpx;">
					应收金额: {{routeParams.receivable_amount}}
				</view>
				<view class="real_pay">
					<view class="">
						实际收款
					</view> 
					<view class="">
						<up-input v-model="sign_amount" type="number" placeholder="" border="none" prefixIcon="￥"
						prefixIconStyle="font-size: 15px;" color="red" fontSize="24" @blur="validatePositive()"></up-input>
					</view>
					
				</view>
				<view class="foot-name">上传凭证</view>
				<view class="img-list">
					<up-upload :fileList="certificate" @afterRead="addImage" @delete="delImage" multiple :maxCount="3"
						:previewFullImage="true"></up-upload>
				</view>
			</view>
		</view>
		<!-- 订单备注 -->
		<view class="payment-method">
			<view class="method-header">
				<view class="header-left">订单备注</view>
			</view>
			<view class="method-foot">
				<up-input placeholder="备注信息" border="surround" v-model="remark"></up-input>
			</view>
		</view>
		<!-- <view class="submit-area-placeholder"></view>
		<view class="submit-area">
			<view class="info">
				<view class="line">
					<text class="label">应收金额：</text>
					<text style="color: #F54E4E;font-size: 28rpx;">￥{{routeParams.receivable_amount}}</text>
				</view>
			</view>
			<view class="submit-btn">
				<up-button text="提交" shape="circle" :loading="submitLoading" :disabled="submitLoading"
					color="rgba(55, 131, 252, 1)" @click="submit"></up-button>
			</view>
		</view> -->

		<view class="fixed-button">
			<up-button text="确认签收" :loading="submitLoading" :disabled="submitLoading" color="rgba(55, 131, 252, 1)"
				@click="submit"></up-button>
		</view>
		<up-picker :show="show" :columns="columns" keyName="label" @cancel="cancel" @confirm="confirm"
			:closeOnClickOverlay="true"></up-picker>
		<up-notify ref="NotifyRef"></up-notify>
	</view>
</template>

<style scoped lang="scss">
	.content {
		width: 100%;
		min-height: 100vh;
		background: rgba(242, 243, 245, 1);

		.goods-box {
			width: 702rpx;
			border-radius: 13rpx;
			background: rgba(255, 255, 255, 1);
			margin: 20rpx auto;
			padding: 30rpx;
			box-sizing: border-box;

			.box-header {
				font-size: 28rpx;
				font-weight: 700;
				color: rgba(2, 14, 36, 1);
			}

			.line {
				width: 654rpx;
				height: 2rpx;
				background: rgba(0, 0, 0, 0.1);
				margin: 20rpx 0rpx;
			}

			.main-box {
				display: flex;
				margin-top: 40rpx;

				.main-left {
					width: 140rpx;
					height: 140rpx;
					margin-right: 20rpx;
					position: relative;

					.gift {
						position: absolute;
						top: 0;
						left: 0;
						width: 60rpx;
						height: 32rpx;
						border-radius: 6rpx 0rpx 0rpx 0rpx;
						background: rgba(55, 131, 252, 1);
						font-size: 22rpx;
						font-weight: 500;
						color: rgba(255, 255, 255, 1);
						text-align: center;
						line-height: 32rpx;
					}
				}

				.main-right {
					width: 100%;
					font-size: 24rpx;
					font-weight: 500;

					.right-header {
						display: flex;
						justify-content: space-between;

						.header-name {
							font-size: 28rpx;
							color: rgba(2, 14, 36, 1);
						}

					}

					.right-mod {
						color: rgba(106, 107, 107, 1);
						margin: 20rpx 0rpx;
					}




					.right-foot {
						display: flex;
						justify-content: space-between;
					}
				}
			}
		}

		.payment-method {
			width: 702rpx;
			border-radius: 13rpx;
			background: rgba(255, 255, 255, 1);
			margin: 20rpx auto;
			padding: 30rpx;
			box-sizing: border-box;

			.method-header {
				display: flex;
				justify-content: space-between;

				.header-left {
					font-size: 32rpx;
					font-weight: bold;
					color: rgba(1, 11, 31, 1);
				}

				.header-right {
					font-size: 24rpx;
					font-weight: 500;
					color: rgba(155, 157, 159, 1);
				}
			}

			.method-line {
				width: 654rpx;
				height: 2rpx;
				background: rgba(0, 0, 0, 0.1);
				margin: 20rpx 0rpx;
			}

			.method-main {
				// display: flex;
				// justify-content: space-between;

				.main-name {
					font-size: 28rpx;
					color: rgba(2, 14, 36, 1);
				}

			}

			.payment-container {
				// display: flex;
				// justify-content: space-between;
				margin-top: 40rpx;
			}

			.method-foot {
				margin: 20rpx 0rpx;
			}
		}

		.content-foot {
			width: 702rpx;
			border-radius: 12rpx;
			background: rgba(255, 255, 255, 1);
			padding: 30rpx;
			box-sizing: border-box;
			margin: 20rpx auto;
			display: flex;
			flex-direction: column;
			gap: 24rpx;
			justify-content: center;
			.real_pay {
				display: flex;
				flex-direction: column;
				gap: 36rpx;
			}
			.foot-name {
				font-size: 28rpx;
				font-weight: 700;
				color: rgba(2, 14, 36, 1);
			}

			.img-list {
				margin-top: 20rpx;
			}

		}

		.submit-area-placeholder {
			width: 100%;
			height: 100rpx;
			padding-top: 20rpx;
			padding-bottom: constant(safe-area-inset-bottom);
			/* 兼容iOS < 11.2 */
			padding-bottom: env(safe-area-inset-bottom);
			/* 兼容iOS 11.2及以上 */
		}

		.submit-area {
			position: fixed;
			left: 0;
			bottom: 0;
			z-index: 10;
			display: flex;
			align-items: center;
			justify-content: space-between;
			width: calc(100% - 80rpx);
			height: 100rpx;
			background-color: #FFF;
			padding: 0 40rpx;
			padding-bottom: constant(safe-area-inset-bottom);
			/* 兼容iOS < 11.2 */
			padding-bottom: env(safe-area-inset-bottom);
			/* 兼容iOS 11.2及以上 */
			box-shadow: 0rpx -4rpx 8rpx 0rpx #efefef;

			.info {
				flex: 2;
				display: flex;
				flex-direction: column;

				.line {
					display: flex;
					gap: 12rpx;
					color: #9C9AA1;
				}

				.label {
					font-size: 28rpx;
				}
			}

			.submit-btn {
				flex: 1;
			}
		}
	}

	.fixed-button {
		position: fixed;
		bottom: 20rpx;
		left: 50%;
		transform: translateX(-50%);
		width: calc(100% - 40rpx);
		padding: 20rpx;
		box-sizing: border-box;
		text-align: center;
	}
</style>